#include "StdAfx.h"
#include ".\wilfile.h"
namespace UIExtended
{

	struct sWixHead
	{
		char Title[44];
		DWORD IndexCount;
	};

	struct sWilHead
	{
		char Title[44];
		DWORD ImageCount;
		DWORD ColorCount;
		DWORD PaletteSize;
	};

	struct sImageInfo
	{
		WORD Width;
		WORD Height;
		BYTE unknow[4];
	};

	bool LoadBitmapWil(LPCTSTR name, DWORD index, CDC& dc/*, CBitmap& Bitmap*/ )
	{
		char szWilFileName[MAX_PATH];
		char szWixFileName[MAX_PATH];

		char szModuleFileName[MAX_PATH];
		GetModuleFileName(0,szModuleFileName,MAX_PATH);
		long nPos=strlen(szModuleFileName);
		while(nPos>0)
		{
			if(szModuleFileName[nPos]=='\\')
			{
				szModuleFileName[nPos]=(char)0;
				strcat(szModuleFileName,"\\data\\");
				break;
			}
			nPos--;
		}
		strcpy(szWilFileName,szModuleFileName);
		strcat(szWilFileName,name);
		strcat(szWilFileName,".wil");

		strcpy(szWixFileName,szModuleFileName);
		strcat(szWixFileName,name);
		strcat(szWixFileName,".wix");

		sWixHead WixHead;
		sWilHead WilHead;
		BYTE* lpPal=NULL;
		DWORD* lpOffs=NULL;
		sImageInfo Image;
		BYTE* pImage=NULL;
		BYTE* pb=NULL;

		FILE*fp;
		fp=fopen(szWixFileName,"rb");
		if(fp!=NULL)
		{
			fread(&WixHead,sizeof(WixHead),1,fp);

			if ( !(index<WixHead.IndexCount) )
			{
				fclose(fp);
				return false;
			}

			std::auto_ptr<DWORD> lpOffs_auto(new DWORD[WixHead.IndexCount]);
			lpOffs=lpOffs_auto.get();

			ZeroMemory(lpOffs,sizeof(DWORD)*WixHead.IndexCount);
			fread(lpOffs,sizeof(DWORD),WixHead.IndexCount,fp);
			fclose(fp);

			fp=fopen(szWilFileName,"rb");
			if(fp!=NULL)
			{
				fread(&WilHead,sizeof(WilHead),1,fp);

				std::auto_ptr<BYTE> lpPal_auto(new BYTE[WilHead.ColorCount*4]);
				lpPal=lpPal_auto.get();

				ZeroMemory(lpPal,sizeof(DWORD)*WilHead.ColorCount);
				fread(lpPal,WilHead.PaletteSize,1,fp);

				fseek(fp,lpOffs[index],SEEK_SET);
				fread(&Image,sizeof(Image),1,fp);

				std::auto_ptr<BYTE> pImage_auto(new BYTE[Image.Height*Image.Width]);
				pImage=pImage_auto.get();

				ZeroMemory(pImage,Image.Height*Image.Width);
				fseek(fp,lpOffs[index]+8,SEEK_SET);
				fread(pImage,Image.Height*Image.Width,1,fp);
				fclose(fp);

				for(WORD i=0;i<Image.Width;i++)
				{
					for(WORD j=0;j<Image.Height;j++)
					{
						pb=&lpPal[pImage[j*Image.Width+i]*4];
						dc.SetPixel(i,Image.Height-j-1,RGB(pb[2],pb[1],pb[0]));
					}
				}
				return true;
			}
		}
		return false;
	}
}